/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
define(function (require, exports, module) {
  var clickFlag = false;
  var $ = require('jquery');
  var msgbox = require('jx_msgbox');
  var cryptojs = require('crypto-js');
  var layIndex = 0 ;
  
  function submitForm()
  {
    if (clickFlag)
      return false;

    if ($.trim($("#USERCODE").val()) == "")
    {
      msgbox.layerbox.alert('#(jxrb.message("login.usercode,public.isNotNull"))');
      $("#USERCODE").focus();
      return false;
    }
    if ($.trim($("#PWD").val()) == "")
    {
      msgbox.layerbox.alert('#(jxrb.message("login.userkey,public.isNotNull"))');
      $("#PWD").focus();
      return false;
    }
    if ($.trim($("#validatecode").val()) == "")
    {
      msgbox.layerbox.alert('#(jxrb.message("login.validatecode,public.isNotNull"))');
      $("#validatecode").focus();
      return false;
    }
    var akeyUrl = "#(jxwebpath.item)akey" ;
    if($("#akey_url").length > 0)
      akeyUrl = $("#akey_url").val() ;
    var loginUrl = "#(jxwebpath.item)logon/" ;
    if($("#login_url").length > 0)
      loginUrl = $("#login_url").val() ;    
    var okUrl = "#(jxwebpath.item)main" ;
    if($("#ok_url").length > 0)
      okUrl = $("#ok_url").val() ;    
    clickFlag = true;
    $.get(akeyUrl,{},function(data)
    {
      var key = cryptojs.enc.Utf8.parse(data);     
      var bytes = cryptojs.AES.encrypt($.trim($("#PWD").val()),key,{iv:key,mode:cryptojs.mode.CBC}) ;
    
      $("#PWD").val(bytes.ciphertext.toString());
      
      msgbox.login({
        url: loginUrl + data
      }, function ()
      {
        if (msgbox.messageCode == "0")
        {
          window.location.href = okUrl;
        }
        else if (msgbox.messageCode == "1")
        {
          openSecurityCodeForm();
        }
      }, function (index)
      {
        msgbox.close();
        $("#PWD").val('');
        $("#validatecode").val('');
        refreshValidateCode();
      });
    });
    clickFlag = false;
    return false;
  }

  function refreshValidateCode()
  {
    var vcodeUrl = "#(jxwebpath.item)validatecode/" ;
    if($("#vcode_url").length > 0)
      vcodeUrl = $("#vcode_url").val() ;        
    $('#img_validatecode').attr("src", vcodeUrl + new Date().getTime());
  }

  $(function ()
  {
    $("#b_submit").on("click", function ()
    {
      submitForm();
    });
    $("#img_validatecode").on("click", function ()
    {
      refreshValidateCode();
    });
    document.onkeydown = function (e)
    {
      if (layIndex != msgbox.layerbox.index)
			{
				layIndex = msgbox.layerbox.index ;
				msgbox.close() ;
				return ;
			}
			layIndex = msgbox.layerbox.index ;
      var ev = document.all ? window.event : e;
      if (ev.keyCode == 13)
        submitForm();
    }
    clickFlag = false;
    $("#USERCODE").focus();
  });

});
